﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Core.Service;
using Microsoft.AspNetCore.Http;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Admin.NET.Application.Entity;
using Admin.NET.Core;
namespace Admin.NET.Application;

/// <summary>
/// 调拨单表服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public partial class SystransferorderService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Systransferorder> _systransferorderRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public SystransferorderService(SqlSugarRepository<Systransferorder> systransferorderRep, ISqlSugarClient sqlSugarClient)
    {
        _systransferorderRep = systransferorderRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询调拨单表 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询调拨单表")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<SystransferorderOutput>> Page(PageSystransferorderInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _systransferorderRep.AsQueryable()
            .LeftJoin<WarehouseModel>((t, w1) => SqlFunc.ToString(w1.Id) == t.FromWarehouse)
            .LeftJoin<WarehouseModel>((t, w1, w2) => SqlFunc.ToString(w2.Id) == t.ToWarehouse)
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), (t, w1, w2) => t.Code.Contains(input.Keyword) || t.FromWarehouse.Contains(input.Keyword) || t.ToWarehouse.Contains(input.Keyword) || t.AgentName.Contains(input.Keyword) || t.GoodsName.Contains(input.Keyword) || t.Remark.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Code), (t, w1, w2) => t.Code.Contains(input.Code.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.FromWarehouse), (t, w1, w2) => t.FromWarehouse.Contains(input.FromWarehouse.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ToWarehouse), (t, w1, w2) => t.ToWarehouse.Contains(input.ToWarehouse.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.AgentName), (t, w1, w2) => t.AgentName.Contains(input.AgentName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.GoodsName), (t, w1, w2) => t.GoodsName.Contains(input.GoodsName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Remark), (t, w1, w2) => t.Remark.Contains(input.Remark.Trim()))
            .WhereIF(input.DocumentStatus.HasValue, (t, w1, w2) => t.DocumentStatus == input.DocumentStatus.Value)
            .WhereIF(input.ApplyDateRange?.Length == 2, (t, w1, w2) => t.ApplyDate >= input.ApplyDateRange[0] && t.ApplyDate <= input.ApplyDateRange[1])
            .WhereIF(input.OutStatus.HasValue, (t, w1, w2) => t.OutStatus == input.OutStatus.Value)
            .WhereIF(input.InStatus.HasValue, (t, w1, w2) => t.InStatus == input.InStatus.Value)
            .WhereIF(input.TransferQuantity != null, (t, w1, w2) => t.TransferQuantity == input.TransferQuantity)
            .WhereIF(input.DeleteTimeRange?.Length == 2, (t, w1, w2) => t.DeleteTime >= input.DeleteTimeRange[0] && t.DeleteTime <= input.DeleteTimeRange[1])
            .Select((t, w1, w2) => new SystransferorderOutput
            {
                Id = t.Id,
                Code = t.Code,
                DocumentStatus = t.DocumentStatus,
                ApplyDate = t.ApplyDate,
                FromWarehouse = t.FromWarehouse,
                FromWarehouseDisplay = w1.WareName ?? t.FromWarehouse,
                ToWarehouse = t.ToWarehouse,
                ToWarehouseDisplay = w2.WareName ?? t.ToWarehouse,
                OutStatus = t.OutStatus,
                InStatus = t.InStatus,
                TransferQuantity = t.TransferQuantity,
                TransferAmount = t.TransferAmount,
                AgentName = t.AgentName,
                GoodsName = t.GoodsName,
                Remark = t.Remark,
                TenantId = t.TenantId,
                OrgId = t.OrgId,
                IsDelete = t.IsDelete,
                DeleteTime = t.DeleteTime,
                CreateTime = t.CreateTime,
                UpdateTime = t.UpdateTime,
                CreateUserId = t.CreateUserId,
                CreateUserName = t.CreateUserName,
                UpdateUserId = t.UpdateUserId,
                UpdateUserName = t.UpdateUserName
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取调拨单表详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取调拨单表详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Systransferorder> Detail([FromQuery] QueryByIdSystransferorderInput input)
    {
        return await _systransferorderRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加调拨单表 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加调拨单表")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddSystransferorderInput input)
    {
        var entity = input.Adapt<Systransferorder>();
        return await _systransferorderRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新调拨单表 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新调拨单表")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateSystransferorderInput input)
    {
        var entity = input.Adapt<Systransferorder>();
        await _systransferorderRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除调拨单表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除调拨单表")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteSystransferorderInput input)
    {
        var entity = await _systransferorderRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _systransferorderRep.FakeDeleteAsync(entity);   //假删除
        //await _systransferorderRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除调拨单表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除调拨单表")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteSystransferorderInput> input)
    {
        var exp = Expressionable.Create<Systransferorder>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _systransferorderRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _systransferorderRep.FakeDeleteAsync(list);   //假删除
        //return await _systransferorderRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 导出调拨单表记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出调拨单表记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageSystransferorderInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportSystransferorderOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "调拨单表导出记录");
    }
    
    /// <summary>
    /// 下载调拨单表数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载调拨单表数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportSystransferorderOutput>(), "调拨单表导入模板");
    }
    
    private static readonly object _systransferorderImportLock = new object();
    /// <summary>
    /// 导入调拨单表记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入调拨单表记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (_systransferorderImportLock)
        {
            var stream = ExcelHelper.ImportData<ImportSystransferorderInput, Systransferorder>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.DocumentStatus == null){
                            x.Error = "单据状态不能为空";
                            return false;
                        }
                        if (x.OutStatus == null){
                            x.Error = "出库状态不能为空";
                            return false;
                        }
                        if (x.InStatus == null){
                            x.Error = "入库状态不能为空";
                            return false;
                        }
                        if (x.TransferQuantity == null){
                            x.Error = "调拨数量不能为空";
                            return false;
                        }
                        return true;
                    }).Adapt<List<Systransferorder>>();
                    
                    var storageable = _systransferorderRep.Context.Storageable(rows)
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.Code), "调拨单号不能为空")
                        .SplitError(it => it.Item.Code?.Length > 64, "调拨单号长度不能超过64个字符")
                        .SplitError(it => it.Item.FromWarehouse?.Length > 64, "调出仓库长度不能超过64个字符")
                        .SplitError(it => it.Item.ToWarehouse?.Length > 64, "调入仓库长度不能超过64个字符")
                        .SplitError(it => it.Item.AgentName?.Length > 64, "经办人长度不能超过64个字符")
                        .SplitError(it => it.Item.GoodsName?.Length > 512, "调拨货品长度不能超过512个字符")
                        .SplitError(it => it.Item.Remark?.Length > 512, "备注长度不能超过512个字符")
                        .SplitInsert(_=> true) // 没有设置唯一键代表插入所有数据
                        .ToStorage();
                    
                    storageable.AsInsertable.ExecuteCommand();// 不存在插入
                    storageable.AsUpdateable.UpdateColumns(it => new
                    {
                        it.Code,
                        it.DocumentStatus,
                        it.ApplyDate,
                        it.FromWarehouse,
                        it.ToWarehouse,
                        it.OutStatus,
                        it.InStatus,
                        it.TransferQuantity,
                        it.TransferAmount,
                        it.AgentName,
                        it.GoodsName,
                        it.Remark,
                        it.DeleteTime,
                    }).ExecuteCommand();// 存在更新
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
